package dal

import (
	"sales-web/server/config"

	logs "github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type DBC struct {
	*gorm.DB
	cfg config.MySQL
}

// Open create mysql connection.
func Open(cfg config.MySQL) (*DBC, error) {
	var (
		dbProxy *gorm.DB
		err     error
		db      DBC
	)
	if cfg.Host != "" {
		url := cfg.GetURL()
		dbProxy, err = gorm.Open(mysql.Open(url), &gorm.Config{})
		if err != nil {
			return nil, err
		}
	} else {
		// sqlite
		// dbProxy, err = gorm.Open(sqlite.Open("sales.db"), &gorm.Config{})
		// if err != nil {
		// 	return nil, err
		// }
	}
	dbProxy.Logger.LogMode(logger.Info)
	err = dbProxy.AutoMigrate(&CustomOrder{}, &User{}, &Country{})
	if err != nil {
		return nil, err
	}
	db = DBC{DB: dbProxy.Debug(), cfg: cfg}

	logs.Info("success to open mysql")
	return &db, nil
}
